﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using DG.Tweening;

namespace linkouqs.Gamekit {

public class ForegroundFader : MonoBehaviour {

        public Ease ease = Ease.OutCirc;
        [Range(0.02f, 5f)]
        public float duraction = 0.5f;
        [Range(0f, 0.9f)]
        public float to;

        public List<Transform> foregrounds = new List<Transform>();

        List<CharacterController2D> m_Characters = new List<CharacterController2D>();

        List<Tweener> m_Tweeners = new List<Tweener>();

        void Awake() {

            List<Renderer> list = new List<Renderer>();

            foreach (var f in foregrounds) {

                var arr = f.GetComponentsInChildren<Renderer>();

                foreach(var r in arr) {

                    if (list.Contains(r)) {
                        continue;
                    }

                    list.Add(r);
                }

            }

            foreach(var r in list) {
                if(r.material != null) {
                    m_Tweeners.Add(r.material.DOFade(to, duraction).SetEase(ease).SetAutoKill(false).Pause());
                }
            }

        }

        void Fade(bool fadeIn) {
            if (fadeIn) {

            foreach(var t in m_Tweeners) {
                t.PlayBackwards();
            }
                return;
            }

            foreach(var t in m_Tweeners) {
                t.PlayForward();
            }
        }

        public void OnTriggerEnter2D(Collider2D collision) {

            CharacterController2D character;

            if (CharacterManager.Instance.TryGetCharacter(collision, out character))
            {
                if (!m_Characters.Contains(character)) {
                    m_Characters.Add(character);
                }

                if(m_Characters.Count > 0) {
                    Fade(false);
                }
            }


        }

        public void OnTriggerExit2D(Collider2D collision) {
            CharacterController2D character;

            if (CharacterManager.Instance.TryGetCharacter(collision, out character))
            {
                if (m_Characters.Contains(character)) {
                    m_Characters.Remove(character);
                }

                if(m_Characters.Count == 0) {

                    Fade(true);
                }
            }
        }

        public void OnDestroy() {
            foreach(var t in m_Tweeners) {
                t.Kill();
            }
            m_Tweeners.Clear();
        }

    }

}
